﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using MLMBonus.Engine;

namespace MLMBonus.DataProvider
{
    public static class BonusData
    {
        private static bool isInitialized = false;
        private static BonusDataProvider provider;

        public static BonusDataProvider Provider
        {
            get
            {
                Initialize();
                return provider;
            }
        }

        private static void Initialize()
        {
            if (!isInitialized)
            {
                BonusDataProviderConfigurationSection dataProviderSection = ConfigurationManager.GetSection("bonusDataProvider") as BonusDataProviderConfigurationSection;
                if (dataProviderSection == null)
                {
                    throw new ConfigurationErrorsException("BonusData is not configured to be used for this application");
                }

                provider = instantiateProvider(dataProviderSection.Type);
                isInitialized = true;
            }
        }

        private static BonusDataProvider instantiateProvider(string providerType)
        {
            Type providerBaseType = typeof(BonusDataProvider);
            if (string.IsNullOrEmpty(providerType))
            {
                throw new ArgumentException("Provider type name is invalid!");
            }

            Type t = Type.GetType(providerType, true, true);
            if (!providerBaseType.IsAssignableFrom(t))
            {
                throw new ArgumentException(string.Format("Provider must implement type {0}.", providerType.ToString()));
            }
            return Activator.CreateInstance(t) as BonusDataProvider;
        }

        public static void Promote(INode Distributor, string OldRank, string NewRank)
        {
            Initialize();
            if (provider != null)
            {
                provider.Promote(Distributor, OldRank, NewRank);
            }
        }

        public static void Pay(IVolume Volume, INode Distributor, string Description, int? Level, decimal Amount)
        {
            Initialize();
            if (provider != null)
            {
                provider.Pay(Volume, Distributor, Description, Level, Amount);
            }
        }

        public static List<INode> GetNodes()
        {
            Initialize();
            if (provider != null)
            {
                return provider.GetNodes();
            }
            return null;
        }
    }
}
